package com.xiaoxie.boot.controller;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.xiaoxie.boot.bean.Book;
import com.xiaoxie.boot.bean.BookType;
import com.xiaoxie.boot.dao.BookMapper;
import com.xiaoxie.boot.excel.BookExcelExportVo;
import com.xiaoxie.boot.excel.BookExcelVo;
import com.xiaoxie.boot.listener.BookListener;
import com.xiaoxie.boot.service.BookService;
import com.xiaoxie.boot.service.BookTypeService;
import com.xiaoxie.boot.utils.DataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.Array;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author xiaoxie
 * @create 2022-02-14 15:03
 */
@Api(tags = "图书API")
@RestController
@Slf4j
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService bookService;

    @Autowired
    private BookTypeService bookTypeService;

    @Autowired
    private BookMapper bookMapper;

    /**
     * 查询所有图书信息
     *
     * @param book
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/queryAllBook")
    @ApiOperation(value = "分页查询", notes = "查询所有图书信息")
    @ApiOperationSupport(author = "小谢")
    public DataInfo queryAllBook(Book book, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "15") Integer limit) {
        PageInfo<Book> bookPageInfo = bookService.selectAllBook(book, page, limit);
        return DataInfo.ok("成功", bookPageInfo.getTotal(), bookPageInfo.getList());
    }

    /**
     * 查询所有图书分类名称
     *
     * @return
     */
    @GetMapping("/queryAllBookType")
    @ApiOperation(value = "分类查询", notes = "查询所有图书分类名称")
    @ApiOperationSupport(author = "小谢")
    public List<BookType> queryAllBookType() {
        List<BookType> bookTypes = bookTypeService.selectAllBookType();
        return bookTypes;
    }

    /**
     * 添加时检查图书名是否存在
     *
     * @param bookName
     * @return
     */
    @GetMapping("/bookExist/{bookName}")
    @ApiOperation(value = "去重", notes = "添加时检查图书名是否存在")
    @ApiOperationSupport(author = "小谢")
    public DataInfo bookExist(@PathVariable String bookName) {
        Book book = bookService.selectByBookName(bookName);
        if (book == null) {
            return DataInfo.ok();
        } else {
            return DataInfo.fail("图书名已存在!");
        }
    }

    /**
     * 图书添加
     *
     * @param book
     * @param request
     * @return
     */
    @PostMapping("/addBook")
    @ApiOperation(value = "新增", notes = "图书添加")
    @ApiOperationSupport(author = "小谢")
    public DataInfo addBook(@RequestBody Book book, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String name = (String) session.getAttribute("name");
        book.setBookNumber(UUID.randomUUID().toString().substring(0, 6));
        log.info(name + "添加了图书：" + book.getBookName());
        int i = bookService.insertSelective(book);
        System.out.println(i);
        if (i == 1) {
            log.info("添加成功");
            return DataInfo.ok();
        } else {
            log.info("添加失败");
            return DataInfo.fail("用户添加失败!");
        }
    }

    /**
     * 修改图书信息
     *
     * @param book
     * @param request
     * @return
     */
    @PutMapping("/editBook")
    @ApiOperation(value = "修改", notes = "修改图书信息")
    @ApiOperationSupport(author = "小谢")
    public DataInfo editBook(@RequestBody Book book, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String name = (String) session.getAttribute("name");
        log.info(name + "修改了图书：" + book.getBookName() + "的信息");
        int i = bookService.updateByPrimaryKeySelective(book);
        if (i == 1) {
            log.info("修改成功");
            return DataInfo.ok();
        } else {
            log.info("修改失败");
            return DataInfo.fail("图书修改失败!");
        }
    }

    /**
     * 删除图书信息
     *
     * @param ids
     * @param request
     * @return
     */
    @DeleteMapping("/deleteBook")
    @ApiOperation(value = "删除", notes = "删除图书信息")
    @ApiOperationSupport(author = "小谢")
    public DataInfo deleteBook(String ids, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String name = (String) session.getAttribute("name");
        List<String> list = Arrays.asList(ids.split(","));
        log.info(name + "试图删除图书信息");
        int i = bookService.deleteBookByIds(list);
        if (i >= 1) {
            log.info("删除了：" + i + "条信息");
            return DataInfo.ok();
        } else {
            log.info("删除失败");
            return DataInfo.fail("删除失败");
        }
    }

    /**
     * 导入图书信息
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/importBook")
    @ApiOperation(value = "导入", notes = "导入图书信息")
    @ApiOperationSupport(author = "小谢")
    public DataInfo importBook(@RequestBody MultipartFile file) throws IOException {
        try {
            EasyExcel.read(file.getInputStream(), BookExcelVo.class, new BookListener(bookMapper))
                    .sheet(0).headRowNumber(1).doRead();
            return DataInfo.ok("导入成功！");
        } catch (Exception e) {
            return DataInfo.fail("导入失败，请下载正确模板，按照模板格式导入！");
        }
    }

    /**
     * 导出图书信息
     *
     * @param ids
     * @throws IOException
     */
    @GetMapping("/exportBook")
    @ApiOperation(value = "导出", notes = "导出图书信息")
    @ApiOperationSupport(author = "小谢")
    public void exportBook(String ids) throws IOException {
        //先根据Id查出所有的图书信息
        String[] list = ids.split(",");
        List<Long> idList = new ArrayList<>();
        for (String s : list) {
            idList.add(Long.valueOf(s));
        }
        List<Book> books = bookService.selectBookByIdS(idList);
        List<BookExcelExportVo> exportVos = new ArrayList<>();
        for (Book book : books) {
            BookExcelExportVo vo = new BookExcelExportVo();
            vo.setBookName(book.getBookName());
            vo.setBookLanguage(book.getBookLanguage());
            vo.setAuthor(book.getAuthor());
            vo.setBookPrice(book.getBookPrice());
            vo.setBookDescription(book.getBookDescription());
            vo.setPress(book.getPress());
            Date publicationTime = book.getPublicationTime();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String s = simpleDateFormat.format(publicationTime);
            vo.setPublicationTime(s);
            vo.setTypeName(book.getTypeName());
            exportVos.add(vo);
        }
        HttpServletResponse response = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("图书信息", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), BookExcelExportVo.class).sheet("模板").doWrite(exportVos);
    }

}
